package com.yuezhi.acl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuezhi.acl.entity.SysUser;
import com.yuezhi.acl.service.SysRoleService;
import com.yuezhi.acl.service.SysUserService;
import com.yuezhi.utils.MD5;
import com.yuezhi.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author boys
 * @since 2020-12-16
 */
@RestController
@RequestMapping("admin/acl/user")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    //获取管理用户分页列表
    @GetMapping("{page}/{limit}")
    public R index(@PathVariable Long page, @PathVariable Long limit, SysUser userQueryVo) {
        Page<SysUser> pageParam = new Page<>(page, limit);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(userQueryVo.getUsername())) {
            wrapper.like("username",userQueryVo.getUsername());
        }

        IPage<SysUser> pageModel = userService.page(pageParam, wrapper);
        return R.success().data("items", pageModel.getRecords()).data("total", pageModel.getTotal());
    }

    //新增管理用户
    @PostMapping("save")
    public R save(@RequestBody SysUser user) {
        user.setPassword(MD5.encrypt(user.getPassword()));
        userService.save(user);
        return R.success();
    }

    //根据用户获取角色数据
    @GetMapping("/toAssign/{userId}")
    public R toAssign(@PathVariable String userId) {
        Map<String, Object> roleMap = roleService.findRoleByUserId(userId);
        return R.success().data(roleMap);
    }

    //根据用户分配角色
    @PostMapping("/doAssign")
    public R doAssign(@RequestParam String userId,@RequestParam String[] roleId) {
        roleService.assignRolesByUser(userId,roleId);
        return R.success();
    }
}

